//
//  NSMutableAttributedStringExtensions.swift
//  ShimaPlayer
//
//  Created by michael on 2025/7/4.
//

import Foundation
import UIKit

extension NSMutableAttributedString {
    
    @discardableResult
    func setColor(for text: String? = nil, color: UIColor) -> NSMutableAttributedString {
        
        let content = string
        
        var result = NSMutableAttributedString(string: content)
        
        if(self.string == content) {
            result = self;
        }
        
        guard let text else {
            let range: NSRange = result.mutableString.range(of: result.string, options: .caseInsensitive)
            result.addAttribute(.foregroundColor, value: color, range: range)
            return result
        }
        
        let matchContent = text
        let range = content.range(of: matchContent, options: .caseInsensitive)
        
        guard let range else {
            return result
        }
        result.addAttribute(.foregroundColor, value: color, range: content.toNSRange(range))
        
        return result
    }
    
}

extension String {
    func toNSRange(_ range: Range<String.Index>) -> NSRange {
        guard let from = range.lowerBound.samePosition(in: utf16), let to = range.upperBound.samePosition(in: utf16) else {
            return NSMakeRange(0, 0)
        }
        return NSMakeRange(utf16.distance(from: utf16.startIndex, to: from), utf16.distance(from: from, to: to))
    }
    
    func toRange(_ range: NSRange) -> Range<String.Index>? {
        guard let from16 = utf16.index(utf16.startIndex, offsetBy: range.location, limitedBy: utf16.endIndex) else {
            return nil
        }
        guard let to16 = utf16.index(from16, offsetBy: range.length, limitedBy: utf16.endIndex) else { return nil }
        guard let from = String.Index(from16, within: self) else {
            return nil
        }
        guard let to = String.Index(to16, within: self) else {
            return nil
        }
        return from ..< to
    }
}
